<template>
	<el-card>
		<div slot="header">
			<span>管理员编辑</span>
		</div>
		<el-form ref="form" :model="form" label-width="80px">
			<el-form-item label="用户名">
				<el-input v-model="form.username" readonly></el-input>
			</el-form-item>
			<el-form-item label="姓名">
				<el-input v-model="form.fullname"></el-input>
			</el-form-item>
			<el-form-item label="角色">
				<el-select v-model="form.role_id" placeholder="请选择" :disable="$route.params.user_id === 1">
					<el-option v-for="item in roel_options" :key="item.role_id" :label="item.role_name"
						:value="item.role_id">
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="性别">
				<el-radio-group v-model="form.sex">
					<el-radio label="男"></el-radio>
					<el-radio label="女"></el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="手机">
				<el-input v-model="form.tel"></el-input>
			</el-form-item>
			<el-form-item label="邮箱">
				<el-input v-model="form.email"></el-input>
			</el-form-item>
			<el-form-item label="图片">
				<Upload_Picture v-model="form.avatar" :data="{type:'avatar'}"></Upload_Picture>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleEdit">保存修改</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script>
import { Admin, Role } from '@/api';
import Upload_Picture from '@/plugins/upload-picture.vue';
export default {
	name: 'Edit',
	components: {
		Upload_Picture,
		},
	mounted() {
		//获取参数
		let { user_id } = this.$route.params;
		this.init(user_id);
	},
	beforeRouteUpdate(to,from,next){
		let { user_id } = to.params;
		next();
		this.init(user_id);
	},
	data() {
		return {
			form: {
				user_id: '',
				username: '',
				fullname: '',
				role_id: '',
				sex: '',
				tel: '',
				email: '',
				avatar: '',
			},
			options: [],
			value: '',
			roel_options: [],
		}
	},
	methods: {
		//初始化
		async init(user_id) {
			//加载角色列表
			let { status: role_status, data: role_data } = await Role.list();
			if (role_status) {
				this.roel_options = role_data;
			};
			//加载管理员资料
			let { status: admin_status, data: profile } = await Admin.info({ user_id });
			if (admin_status) {
				//还原表单数据
				this.form = profile;
			};

		},
		//保存修改
		async handleEdit() {
			let { user_id } = this.form;
			try {
				let valid = await this.$refs.form.validate();
				if (valid) {
					let { status, msg } = await Admin.edit({ ...this.form });
					if (status) {
						this.$router.push('../list')
						this.$message.success(msg);
					} else {
						this.$message.error(msg);
					}
				}
			} catch { }
		},
	},
}
</script>

